package com.xindaoapp.happypet.ui;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.DianZanListData;
import com.xindaoapp.happypet.bean.ReYiListData;
import com.xindaoapp.happypet.fragments.UserInfoFragment;
import com.xindaoapp.happypet.utils.BitmapUtil;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.CircleImageView;

/**
 * 查看榜单Fragment
 * 
 * @author Yangqing
 * 
 */
public class RankingFragment extends BaseFragment {

    private PullToRefreshListView vPullToRefreshListView;
    private boolean isZanList;
    private String mTid;



    public static RankingFragment newInstance(int position, String tid) {
        RankingFragment fragment = new RankingFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(Constants.KEY_POSITION, position == 0 ? true : false);
        bundle.putString(Constants.KEY_TID, tid);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return mView = inflater.inflate(R.layout.layout_rankinglist, container, false);
    }

    @Override
    protected void initViews() {

        isZanList = getArguments().getBoolean(Constants.KEY_POSITION);
        mTid = getArguments().getString(Constants.KEY_TID);

        vPullToRefreshListView = (PullToRefreshListView) mView.findViewById(R.id.pullListView);
        vPullToRefreshListView.setMode(Mode.PULL_FROM_START);
        vPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loadDatas();
            }
        });
    }



    @Override
    protected void loadDatas() {
        if (isZanList) {
            HappyPetApplication
                    .get()
                    .getMoccaApi()
                    .getDianZanListData(mTid, Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                            new IRequest<DianZanListData>() {

                                @Override
                                public void request(DianZanListData t) {
                                    if (null != t) {
                                        onDataArrived(true);
                                        if (t.array.size() == 0) {
                                            onDataArrivedEmpty();
                                        } else {
                                            vPullToRefreshListView.setAdapter(new RankingAdapter(
                                                    getActivity(), t.array, Constants.PAGE_SIZE,
                                                    R.layout.item_ranking, R.layout.item_loading));
                                        }
                                    } else {
                                        onDataArrived(false);
                                    }
                                    vPullToRefreshListView.onRefreshComplete();
                                }
                            });
        } else {
            HappyPetApplication
                    .get()
                    .getMoccaApi()
                    .getReYiListData(mTid, Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                            new IRequest<ReYiListData>() {

                                @Override
                                public void request(ReYiListData t) {
                                    if (null != t) {
                                        onDataArrived(true);
                                        if (t.array.size() == 0) {
                                            onDataArrivedEmpty();
                                        } else {
                                            vPullToRefreshListView.setAdapter(new ReYiAdapter(
                                                    getActivity(), t.array, Constants.PAGE_SIZE,
                                                    R.layout.item_reyi, R.layout.item_loading));
                                        }
                                    } else {
                                        onDataArrived(false);
                                    }
                                    vPullToRefreshListView.onRefreshComplete();
                                }
                            });
        }
    }


    class ViewHolder {
        public CircleImageView iv_icon;
        public TextView tv_name, tv_time, tv_sex, tv_city, tv_rank, tv_zancount;
        public ImageView iv_img, iv_rank, iv_zan, iv_canyu, iv_sex_boy, iv_sex_girl;

    }

    class RankingAdapter extends XinDaoBaseAdapter<DianZanListData.DianZanInfo> {

        public RankingAdapter(Context context, List<DianZanListData.DianZanInfo> iniData,
                int pageSize, int res, int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent,
                final DianZanListData.DianZanInfo value) {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.iv_icon = (CircleImageView) convertView.findViewById(R.id.iv_icon);
                holder.iv_img = (ImageView) convertView.findViewById(R.id.iv_img);
                holder.iv_sex_boy = (ImageView) convertView.findViewById(R.id.iv_sex_boy);
                holder.iv_sex_girl = (ImageView) convertView.findViewById(R.id.iv_sex_girl);
                holder.iv_rank = (ImageView) convertView.findViewById(R.id.iv_rank);
                holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
                holder.tv_city = (TextView) convertView.findViewById(R.id.tv_city);
                holder.tv_rank = (TextView) convertView.findViewById(R.id.tv_rank);
                holder.tv_zancount = (TextView) convertView.findViewById(R.id.tv_zancount);
                convertView.setTag(holder);
            }


            ImageLoader.getInstance().displayImage(value.userface, holder.iv_icon,
                    BitmapUtil.getPersonLoading());

            android.view.ViewGroup.LayoutParams lp1 = holder.iv_img.getLayoutParams();
            // lp1.width = CommonParameter.sScreenWidth / 2;
            // lp1.height = CommonParameter.sScreenWidth / 2;
            // lp1.width = holder.iv_img.getWidth();
            // lp1.height =
            // lp1.width * Integer.parseInt(value.pics.get(0).height)
            // / Integer.parseInt(value.pics.get(0).width);

            lp1.width = (CommonParameter.sScreenWidth - CommonUtil.dip2px(mContext, 110)) * 4 / 5;
            lp1.height =
                    lp1.width * Integer.parseInt(value.pics.get(0).height)
                            / Integer.parseInt(value.pics.get(0).width);

            // lp1.width = (CommonParameter.sScreenWidth - CommonUtil.dip2px(mContext, 110)) * 4 /
            // 5;
            // lp1.height =
            // (CommonParameter.sScreenWidth - CommonUtil.dip2px(mContext, 110)) * 4 / 5
            // * Integer.parseInt(value.pics.get(0).height)
            // / Integer.parseInt(value.pics.get(0).width);
            holder.iv_img.setScaleType(ScaleType.FIT_XY);
            // holder.iv_img.setScaleType(ScaleType.CENTER_CROP);
            holder.iv_img.setLayoutParams(lp1);
            if (value.pics.size() != 0) {
                ImageLoader.getInstance().displayImage(value.pics.get(0).url, holder.iv_img);
            }
            if (value.pics.size() != 0) {
                ImageLoader.getInstance().displayImage(value.pics.get(0).url, holder.iv_img);
            }

            holder.tv_zancount.setText(value.goodNumber);
            holder.tv_name.setText(value.author);
            holder.tv_time.setText(CommonUtil.formatTimeForListCommon(value.date));
            // TODO 排名前三, 直接显示图片
            holder.iv_rank.setVisibility(View.VISIBLE);
            holder.tv_rank.setVisibility(View.GONE);
            if (value.rank.equals("1")) {
                holder.iv_rank.setImageResource(R.drawable.no1);
            } else if (value.rank.equals("2")) {
                holder.iv_rank.setImageResource(R.drawable.no2);
            } else if (value.rank.equals("3")) {
                holder.iv_rank.setImageResource(R.drawable.no3);
            } else {
                holder.iv_rank.setVisibility(View.GONE);
                holder.tv_rank.setVisibility(View.VISIBLE);
                holder.tv_rank.setText(value.rank);
            }

            // TODO 这里需要做判断
            /** 这里可能得不到用户 后台正在调试 */
            if (value.userinfo.province != null) {
                holder.tv_city.setText(value.userinfo.province);
            }
            holder.iv_sex_boy.setVisibility(View.GONE);
            holder.iv_sex_girl.setVisibility(View.GONE);
            if (value.userinfo.sex.equals("1")) {
                holder.iv_sex_boy.setVisibility(View.VISIBLE);
            } else if (value.userinfo.sex.equals("2")) {
                holder.iv_sex_girl.setVisibility(View.VISIBLE);
            }

            holder.iv_icon.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    // 他人中心
                    Intent intent =
                            new Intent(getActivity(),
                                    com.xindaoapp.happypet.activity.MainActivity.class);
                    intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                            UserInfoFragment.class.getCanonicalName());
                    Bundle bundle = new Bundle();
                    bundle.putString(Constants.KEY_UID, value.authorid);
                    bundle.putString(Constants.KEY_USERNAME, value.author);
                    bundle.putString(Constants.KEY_USERFACE, value.userface);
                    intent.putExtra(Constants.KEY_BUNDLE, bundle);
                    getActivity().startActivity(intent);
                }
            });

            convertView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent intent =
                            new Intent(getActivity(),
                                    com.xindaoapp.happypet.ui.PostDetailActivity.class);
                    intent.putExtra(Constants.KEY_POST_TID, value.tid);
                    startActivity(intent);
                }
            });

            return convertView;
        }

        @Override
        protected List<DianZanListData.DianZanInfo> parseResult(
                List<DianZanListData.DianZanInfo> list) {
            // TODO Auto-generated method stub
            for (int i = list.size() - 1; i >= 0; i--) {
                if (getResult().contains(list.get(i))) {
                    list.remove(list.get(i));
                }
            }
            return list;
        }

        @Override
        public void nextPage(
                int start,
                int size,
                final com.xindaoapp.happypet.adapter.XinDaoBaseAdapter.ILoadNextPageData<DianZanListData.DianZanInfo> iLoadNextPageData) {
            getMoccaApi().getDianZanListData(mTid, start, size, new IRequest<DianZanListData>() {
                @Override
                public void request(DianZanListData t) {
                    iLoadNextPageData.loadNextPageData(t == null ? null : t.array);
                }
            });
        }

    }

    class ReYiAdapter extends XinDaoBaseAdapter<ReYiListData.ReYiInfo> {

        public ReYiAdapter(Context context, List<ReYiListData.ReYiInfo> iniData, int pageSize,
                int res, int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent,
                final ReYiListData.ReYiInfo value) {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.iv_icon = (CircleImageView) convertView.findViewById(R.id.iv_icon);
                holder.iv_img = (ImageView) convertView.findViewById(R.id.iv_img);
                holder.iv_zan = (ImageView) convertView.findViewById(R.id.iv_zan);
                holder.iv_sex_boy = (ImageView) convertView.findViewById(R.id.iv_sex_boy);
                holder.iv_sex_girl = (ImageView) convertView.findViewById(R.id.iv_sex_girl);
                holder.iv_canyu = (ImageView) convertView.findViewById(R.id.iv_canyu);
                holder.iv_rank = (ImageView) convertView.findViewById(R.id.iv_rank);
                holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
                holder.tv_city = (TextView) convertView.findViewById(R.id.tv_city);
                holder.tv_rank = (TextView) convertView.findViewById(R.id.tv_rank);
                holder.tv_zancount = (TextView) convertView.findViewById(R.id.tv_zancount);
                convertView.setTag(holder);
            }



            ImageLoader.getInstance().displayImage(value.userface, holder.iv_icon,
                    BitmapUtil.getPersonLoading());

            android.view.ViewGroup.LayoutParams lp2 = holder.iv_img.getLayoutParams();
            lp2.width = (CommonParameter.sScreenWidth - CommonUtil.dip2px(mContext, 110)) * 4 / 5;
            lp2.height =
                    lp2.width * Integer.parseInt(value.pics.get(0).height)
                            / Integer.parseInt(value.pics.get(0).width);
            // lp2.width = (CommonParameter.sScreenWidth - CommonUtil.dip2px(mContext, 110)) * 4 /
            // 5;
            // lp2.height =
            // (CommonParameter.sScreenWidth - CommonUtil.dip2px(mContext, 110)) * 4 / 5
            // * Integer.parseInt(value.pics.get(0).height)
            // / Integer.parseInt(value.pics.get(0).width);
            // lp2.width = CommonParameter.sScreenWidth / 2;
            // lp2.height = CommonParameter.sScreenWidth / 2;
            // lp2.width = (CommonParameter.sScreenWidth - CommonUtil.dip2px(mContext, 140)) * 8 /
            // 9;
            // lp2.height = (CommonParameter.sScreenWidth - CommonUtil.dip2px(mContext, 140)) * 8 /
            // 9;
            // holder.iv_img.setScaleType(ScaleType.FIT_XY);
            holder.iv_img.setScaleType(ScaleType.FIT_XY);
            holder.iv_img.setLayoutParams(lp2);
            if (value.pics.size() != 0) {
                ImageLoader.getInstance().displayImage(value.pics.get(0).url, holder.iv_img);
            }


            holder.tv_zancount.setText(value.replies);
            holder.tv_name.setText(value.author);
            holder.tv_time.setText(CommonUtil.formatTimeForListCommon(value.addtime));
            // TODO 排名前三, 直接显示图片
            holder.iv_rank.setVisibility(View.VISIBLE);
            holder.tv_rank.setVisibility(View.GONE);
            if (value.topnum.equals("1")) {
                holder.iv_rank.setImageResource(R.drawable.no1);
            } else if (value.topnum.equals("2")) {
                holder.iv_rank.setImageResource(R.drawable.no2);
            } else if (value.topnum.equals("3")) {
                holder.iv_rank.setImageResource(R.drawable.no3);
            } else {
                holder.iv_rank.setVisibility(View.GONE);
                holder.tv_rank.setVisibility(View.VISIBLE);
                holder.tv_rank.setText(value.topnum);
            }

            holder.tv_city.setText(value.city);

            holder.iv_sex_boy.setVisibility(View.GONE);
            holder.iv_sex_girl.setVisibility(View.GONE);
            if (value.gender.equals("1")) {
                holder.iv_sex_boy.setVisibility(View.VISIBLE);
            } else if (value.gender.equals("2")) {
                holder.iv_sex_girl.setVisibility(View.VISIBLE);
            }

            holder.iv_canyu.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO 进帖子详情 , 并且弹出键盘 ,回复
                    Intent intent =
                            new Intent(getActivity(),
                                    com.xindaoapp.happypet.ui.PostDetailActivity.class);
                    intent.putExtra(Constants.KEY_POST_TID, value.tid);
                    intent.putExtra(Constants.KEY_FROM_ACTIVITY, "canyu");
                    startActivity(intent);
                }
            });
            holder.tv_zancount.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO 进帖子详情 , 并且弹出键盘 ,回复
                    Intent intent =
                            new Intent(getActivity(),
                                    com.xindaoapp.happypet.ui.PostDetailActivity.class);
                    intent.putExtra(Constants.KEY_POST_TID, value.tid);
                    intent.putExtra(Constants.KEY_FROM_ACTIVITY, "canyu");
                    startActivity(intent);
                }
            });

            holder.iv_icon.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    // 他人中心
                    Intent intent =
                            new Intent(getActivity(),
                                    com.xindaoapp.happypet.activity.MainActivity.class);
                    intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                            UserInfoFragment.class.getCanonicalName());
                    Bundle bundle = new Bundle();
                    bundle.putString(Constants.KEY_UID, value.authorid);
                    bundle.putString(Constants.KEY_USERNAME, value.author);
                    bundle.putString(Constants.KEY_USERFACE, value.userface);
                    intent.putExtra(Constants.KEY_BUNDLE, bundle);
                    getActivity().startActivity(intent);
                }
            });

            convertView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    Intent intent =
                            new Intent(getActivity(),
                                    com.xindaoapp.happypet.ui.PostDetailActivity.class);
                    intent.putExtra(Constants.KEY_POST_TID, value.tid);
                    startActivity(intent);
                }
            });

            return convertView;
        }

        @Override
        protected List<ReYiListData.ReYiInfo> parseResult(List<ReYiListData.ReYiInfo> list) {
            // TODO Auto-generated method stub
            for (int i = list.size() - 1; i >= 0; i--) {
                if (getResult().contains(list.get(i))) {
                    list.remove(list.get(i));
                }
            }
            return list;
        }

        @Override
        public void nextPage(
                int start,
                int size,
                final com.xindaoapp.happypet.adapter.XinDaoBaseAdapter.ILoadNextPageData<ReYiListData.ReYiInfo> iLoadNextPageData) {
            getMoccaApi().getReYiListData(mTid, start, size, new IRequest<ReYiListData>() {
                @Override
                public void request(ReYiListData t) {
                    iLoadNextPageData.loadNextPageData(t == null ? null : t.array);
                }
            });
        }

    }


}
